package com.llkj.qingnianguoxue.login;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.text.SpannableString;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.jm.chat.database.UserEntry;
import com.jm.chat.utils.SharePreferenceManager;
import com.llkj.qingnianguoxue.MainActivity;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.EventChangeUserBean;
import com.llkj.qingnianguoxue.bean.LoginBean;
import com.llkj.qingnianguoxue.bean.response.ResponseData;
import com.llkj.qingnianguoxue.circle.GroupDetailActivity;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.JGuangUtil;
import com.llkj.qingnianguoxue.util.KeyBoardUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.TextViewUtil;
import com.llkj.qingnianguoxue.util.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.RequestCallback;
import cn.jpush.im.android.api.model.DeviceInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

import static com.llkj.qingnianguoxue.base.ConstantUserInfo.HUANXIN_PWD;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements PlatformActionListener, DialogUtil.DialogClickListener {
    @BindView(R.id.et_phone)
    EditText etPhone;//手机号
    @BindView(R.id.et_code)
    EditText etCode;//验证码
    @BindView(R.id.tv_get_code)
    TextView btnGetCode;//获取验证码
    @BindView(R.id.ll_agreement)
    LinearLayout llAgrement;//同意协议
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;//协议
    private String mLoginOut;
    @BindView(R.id.tv_login)
    public TextView btnLogin;
    @BindView(R.id.et_recommend)
    EditText etRecommendCode;

    private TimeCount time;//倒计时
    private int durationTime = 60 * 1000;
    private Dialog mLoginTypeDialog;

    private String mPlatUserHead, mPlatUserName, mPlatUserId;
    private int mLoginMehtodType = 0;
    private boolean isMaster = false;//是否是老师  1不是  2是
    private String recommendCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        setTitle("登录", true, TITLE_TYPE_IMG, R.drawable.icon_back_white, true, TITLE_TYPE_TEXT, "随便逛逛");
        Intent intent = getIntent();
        mLoginOut = intent.getStringExtra("login_out");

        initView();
    }

    private void initView() {
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT, rlTitle, R.color.colorFE4A49);
//        systemBarTintManager.setStatusBarTintColor(ContextCompat.getColor(this, R.color.colorFE4A49));
        titleLineBottom.setVisibility(View.GONE);
        rlTitle.setBackgroundColor(ContextCompat.getColor(this, R.color.colorFE4A49));
        tvTitle.setTextColor(ContextCompat.getColor(this, R.color.white));
        tvRight.setTextColor(ContextCompat.getColor(this, R.color.white));
        llAgrement.setSelected(true);

        String content = getString(R.string.login_agreement);
        SpannableString spannableString = TextViewUtil.getForegroundColorSpan(this, content, 5, content.length(), R.color.colorFE4A49);
        tvAgreement.setText(spannableString);

        boolean isRemember = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.IS_REMEMBER_PASSWORD);
        String phone = MyApplication.getInstance().sputil.getString(ConstantUserInfo.MOBILE);
        etPhone.setText(phone);

        time = new TimeCount(durationTime, 1000);
        mLoginTypeDialog = DialogUtil.showLoginTypeDialog(this, this);
    }

    @Override
    protected void rightDoWhat() {
        super.rightDoWhat();
        if ("1".equals(mLoginOut) || "2".equals(mLoginOut)) {
            startActivity(MainActivity.class);
        }
        finish();
    }

    @OnClick({R.id.tv_login, R.id.ll_agreement, R.id.ll_wechat, R.id.ll_qq, R.id.ll_sign, R.id.tv_get_code, R.id.tv_agreement})
    public void onClick(View v) {
        String phone = etPhone.getText().toString().trim();
        switch (v.getId()) {
            case R.id.tv_get_code://获取验证码
                if (!StringUtils.isPhoneNumber(phone)) {
                    ToastUtil.makeLongText(this, "请输入正确的手机号格式");
                    return;
                }
                time.start();
                isMaster = false;
                loadWaitDialog();
                HttpMethod.loginFormcode(this, this, phone, "1");
                break;
            case R.id.tv_login://登录
                if (!StringUtils.isPhoneNumber(phone)) {
                    ToastUtil.makeLongText(this, "请输入正确的手机号格式");
                    return;
                }
                String code = etCode.getText().toString();
                if (StringUtils.isEmpty(code)) {
                    ToastUtil.makeLongText(this, "请输入验证码");
                    return;
                }
                recommendCode = etRecommendCode.getText().toString();
                mLoginMehtodType = 1;
                isShowIndentity();
                break;
            case R.id.tv_agreement://同意协议
                Bundle bundle = new Bundle();
                bundle.putInt("from_class", 1);
                startActivity(AgreementActivity.class, bundle);
                break;
            case R.id.ll_agreement://同意协议
                if (llAgrement.isSelected()) {
                    llAgrement.setSelected(false);
                } else {
                    llAgrement.setSelected(true);
                }
                break;
            case R.id.ll_wechat://微信
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechat);
                break;
            case R.id.ll_qq://qq
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);
                break;
            case R.id.ll_sign://微博
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sina);
                break;
        }
    }

    private void isShowIndentity() {
        if (isMaster) {
//            mLoginTypeDialog.show();
            dialogClick(2);
        } else {
            dialogClick(1);
        }
    }

    private void setModifyContent(String isNewUser) {
        if ("2".equals(isNewUser)) {//新用户，显示填写邀请码
            DialogUtil.modifyGroupDialog(this, InputType.TYPE_CLASS_TEXT, "邀请码", null, new DialogUtil.DialogRechargeClickListener() {
                @Override
                public void rechargeClick(int type, String content) {
                    KeyBoardUtil.hideSoftKeyboard(LoginActivity.this);
                    if (type == 1) {//
                        recommendCode = content;
                    }
                    isShowIndentity();
                }
            }).show();
        } else {//老用户，显示选择身份弹框
            isShowIndentity();
        }
    }

    @Override
    public void dialogClick(int type) {
        //1普通用户,2老师
        String phone = etPhone.getText().toString().trim();
        String code = etCode.getText().toString();
        setLogin(type, phone, code, mPlatUserName, mPlatUserHead, mPlatUserId);
    }

    /**
     * 1.2 登录
     *
     * @param mobile       电话(type = 1 必传)
     * @param code         验证码
     * @param identityType 1 普通用户 2 老师
     * @param username     QQ微信用户名
     * @param userpic      QQ微信图像
     * @param w_id         第三方返回ID
     */
    private void setLogin(int identityType, String mobile, String code, String username, String userpic, String w_id) {
        loadWaitDialog();
        HttpMethod.loginLogin(this, this, String.valueOf(identityType), mobile, code, String.valueOf(mLoginMehtodType), username, userpic, w_id, recommendCode);
    }

    private void authorize(Platform plat) {
        if (plat == null) {
            return;
        }
//        //判断指定平台是否已经完成授权
//        if (plat.isAuthValid()) {
//            String userId = plat.getDb().getUserId();
//            if (userId != null) {
//                return;
//            }
//        }
//        if (plat.isAuthValid()) {
//            plat.removeAccount(true);
//            return;
//        }
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(false);
//        //获取用户资料
        plat.showUser(null);
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        if (action == Platform.ACTION_USER_INFOR) {
            PlatformDb platDB = platform.getDb();//获取数平台数据DB
            //通过DB获取各种数据
//            platDB.getToken();

            mPlatUserHead = platDB.getUserIcon();
            mPlatUserId = platDB.getUserId();
            mPlatUserName = platDB.getUserName();
//                userName = platDB.getUserGender();//性別

            mLoginMehtodType = 0;
            if (Wechat.NAME.equals(platform.getName())) {
                mLoginMehtodType = 2;
            } else if (QQ.NAME.equals(platform.getName())) {
                mLoginMehtodType = 3;
            } else if (SinaWeibo.NAME.equals(platform.getName())) {
                mLoginMehtodType = 4;
            }

            if (mLoginMehtodType != 0) {
                loadWaitDialog();
                HttpMethod.loginIsMaster(this, this, mPlatUserId,mLoginMehtodType);
            }
        }
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        //授权失败
        ToastUtil.makeLongText(this, "授权失败");
    }

    @Override
    public void onCancel(Platform platform, int i) {
        //取消授权
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_LOGIN_LOGIN) {
            ResponseData<LoginBean> responseBean = GsonUtil.fromJson(data, LoginBean.class);
            final LoginBean loginBean = responseBean.getUser();
            if (loginBean != null) {
                MyApplication.getInstance().sputil.put(ConstantUserInfo.ISLOGIN, true);
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_ID, loginBean.getUid());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.TOKEN, loginBean.getToken());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_HEAD, loginBean.getUserpic());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_NAME, loginBean.getUsername());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_BALANCE, loginBean.getBalance());//余额
                MyApplication.getInstance().sputil.put(ConstantUserInfo.MOBILE, loginBean.getMobile());
                MyApplication.getInstance().sputil.put(ConstantUserInfo.IS_PUSH, loginBean.getIs_push());//
                String identityType = responseBean.getGenre();
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_IDENTITY_TYPE, identityType);
                MyApplication.getInstance().sputil.put(ConstantUserInfo.MASTER_ID, loginBean.getMaster_id());//导师id
                MyApplication.getInstance().sputil.put(ConstantUserInfo.CHAT_LOGIN_ID, loginBean.getHx_id());//聊天登陆id
                MyApplication.getInstance().sputil.put(ConstantUserInfo.USER_SIGNATURE, loginBean.getSignature());//个性签名

                MyApplication.getInstance().sputil.put(ConstantUserInfo.QQ_ID, loginBean.getQq_id());//qq
                MyApplication.getInstance().sputil.put(ConstantUserInfo.WECHAT_ID, loginBean.getWei_id());//wechat
                MyApplication.getInstance().sputil.put(ConstantUserInfo.SINA_ID, loginBean.getWeibo_id());//sina

                JGuangUtil.loginHuanXin(loginBean.getHx_id(), loginBean.getUsername());

                if ("1".equals(mLoginOut)) {
                    EventBus.getDefault().post(new EventChangeUserBean());
//                    startActivity(MainActivity.class);
                }else if ("2".equals(mLoginOut)) {
                    startActivity(MainActivity.class);
                }
                setResult(RESULT_OK);
                myFinish();
            }
        } else if (method == HttpMethod.HTTP_LOGIN_FORMCODE) {
            LoginBean response = GsonUtil.GsonToBean(data, LoginBean.class);
            if (response != null) {
                isMaster = "2".equals(response.getIs_master()) ? true : false;
                String isNewUser = response.getIs_user();
                if ("2".equals(isNewUser)) {
                    etRecommendCode.setVisibility(View.VISIBLE);
                }
            }
        } else if (method == HttpMethod.HTTP_LOGIN_IS_MASTER) {
            LoginBean response = GsonUtil.GsonToBean(data, LoginBean.class);
            if (response != null) {
                isMaster = "2".equals(response.getIs_master()) ? true : false;
                String isNewUser = response.getIs_user();
                setModifyContent(isNewUser);
//                isShowIndentity();
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ("1".equals(mLoginOut) || "2".equals(mLoginOut)) {
                startActivity(MainActivity.class);
            }
            finish();
        }
        return false;
    }

    @Override
    protected void leftDoWhat() {
        if ("1".equals(mLoginOut) || "2".equals(mLoginOut)) {
            startActivity(MainActivity.class);
        }
        super.leftDoWhat();
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {// 计时完毕
            if (btnGetCode != null) {
                btnGetCode.setText("重新发送");
                btnGetCode.setClickable(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程
            if (btnGetCode != null) {
                btnGetCode.setClickable(false);//防止重复点击
                btnGetCode.setText(millisUntilFinished / 1000 + "s");
            }
        }
    }
}
